<?php

class Employee{
	const MAX_EDIT_TIME = 60;

	function __construct(){}

	function save($token=""){
		($this->id) ? $this->update($token) : $this->insert();
	}

	static function getAll(){
		static $stmt;
		if(!$stmt){
			$stmt = getConnection()->prepare("SELECT * FROM employees");
		}
		$stmt->execute();
		return $stmt->fetchAll(PDO::FETCH_CLASS, "Employee");
	}

	static function get($id, $editMode = false){
		static $stmt;
		if(!$stmt){
			$stmt = getConnection()->prepare("SELECT * FROM employees WHERE id=:id");
			$stmt->bindParam(":id", $id);
		}
		$stmt->setFetchMode(PDO::FETCH_CLASS, "Employee");

		$stmt->execute();
		$res = $stmt->fetch();
		if(!$res){
			throw new Exception("No employee found!");
		}
		return $res;
	}

	function editMode(){
		$this->editMode = time() + self::MAX_EDIT_TIME;
		$this->update($this->token);
		return self::get($id);
	}

	public function delete(){
		static $deleteStmt;
		if(!$deleteStmt){
			$deleteStmt = getConnection()->prepare("DELETE FROM employees WHERE id=:id");
			$deleteStmt->bindParam(":id", $this->id);
		}
		if($this->editMode < time() - self::MAX_EDIT_TIME){
			$deleteStmt->execute();
		}else{
			throw new Exception("Cannot delete. Record has currently pending update!");
		}
	}

	private function update($token){
		static $updateStmt;
		if(!$updateStmt){
			$updateStmt = getConnection()->prepare("UPDATE employees SET editMode=:editMode, name=:name, gender=:gender, token=:token WHERE id=:id");
			$updateStmt->bindParam(":id", 	$this->id);
			$updateStmt->bindParam(":name",	$this->name);
			$updateStmt->bindParam(":gender", $this->gender);
			$updateStmt->bindParam(":token",$this->token);
			$updateStmt->bindParam(":editMode",$this->editMode);
		}

		$emp = Employee::get($this->id);
		if($emp->token!=$token){
			throw new Exception("Invalid update token");
		}else{
			if($this->name!=$emp->name || $this->gender!=$emp->gender){
				$this->token = time();
			}

			$updateStmt->execute();
		}
	}

	private function insert(){
		static $insertStmt;
		if(!$insertStmt){
			$insertStmt = getConnection()->prepare("INSERT INTO employees(id, name, gender, token) VALUES(NULL, :name, :gender, :token)");
			$insertStmt->bindParam(":name",	$this->name);
			$insertStmt->bindParam(":gender", $this->gender);
			$insertStmt->bindParam(":token",$this->token);
		}
		$this->token = time();
		$insertStmt->execute();
		$this->id = getConnection()->lastInsertId();
	}

	public function estimatedTimeToAllowDelete(){
		$eta = $this->editMode-(time()-Employee::MAX_EDIT_TIME);
		return ($eta > 0)? $eta: 0;
	}

	public function editUrl(){
		return "index.php?act=edit&id=".$this->id;
	}
	public function deleteUrl(){
		return "index.php?act=delete&id=".$this->id;
	}
}